package com.erlinyou.im.dao.repository.chat;

import java.util.ArrayList;
import java.util.List;

import org.springframework.data.jpa.repository.Query;

import com.erlinyou.base.dao.BaseRepository;
import com.erlinyou.im.model.chat.ChatMessage;

public interface ChatMessageRepository extends BaseRepository<ChatMessage, String> {
	public boolean existsByClientid(String clientid);
	public int deleteByGid(String gid);
	public ChatMessage findByFromIdAndId(Long fromId,String id);
	
	

	@Query(value="SELECT * from tchat_message c WHERE gid = ?1 AND ctype = ?5 and c.ct >= ?2 AND rev = 0 ORDER BY ct DESC LIMIT ?3,?4",nativeQuery=true)
	public List<ChatMessage> getMsg(String gid, Long inGourpTime , Integer start, Integer page,int ctype);

	@Query(value="SELECT count(*) from tchat_message c WHERE gid = ?2 and id NOT in(SELECT xid from tchat_message_del WHERE userid = ?1)",nativeQuery=true)
	public Integer getCount(String userid, String gid);

/*
	@Modifying
	@Query(value="DELETE from chat_message where cfrom = ?1 and cto = ?2",nativeQuery=true)
	public int deleteByGid(Long userId, Integer groupid);
	*/
/*
	@Query(value="SELECT * from tchat_message c WHERE gid = ?2 AND ctype = ?5 and id NOT in(SELECT xid from tchat_message_del WHERE userid = ?1) AND rev = 0 ORDER BY ct DESC LIMIT ?3,?4",nativeQuery=true)
	public List<ChatMessage> getMsg(String userId, String gid, Integer start, Integer page,int ctype);*/
	@Query(value="SELECT * from tchat_message c WHERE gid = ?1 AND ctype = ?4 AND rev = 0 ORDER BY ct DESC LIMIT ?2,?3",nativeQuery=true)
	public List<ChatMessage> getMsg(String gid, Integer start, Integer page,int ctype);
	
	@Query(value="SELECT * from tchat_message c WHERE gid = ?2 AND ctype = ?5 AND (fromId = ?1 or visitorId = ?1) AND rev = 0 ORDER BY ct DESC LIMIT ?3,?4",nativeQuery=true)
	public List<ChatMessage> getMsgCallCenter(Long userId, String gid, Integer page, Integer rows,int ctype);
	
	public List<ChatMessage> findAllByCt(ArrayList<Long> arrayList);
	@Query(value="SELECT * from tchat_message c WHERE gid = ?2 AND ctype = ?3 and id NOT in(SELECT xid from tchat_message_del WHERE userid = ?1) AND rev = 0 ORDER BY ct DESC limit 1",nativeQuery=true)
	public ChatMessage findByfromIdAndtoId(Long userId,String gid, Integer ctype);
	
	public ChatMessage findByClientid(String clientid);
	
	public List<ChatMessage> findByCtype(int ctype);
	@Query(value="SELECT * FROM tchat_message WHERE id in(SELECT xid from tchat_message_del WHERE userid = ?1)",nativeQuery=true)
	public List<ChatMessage> getMsgDel(String userId);
}
